import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_webview_plugin/flutter_webview_plugin.dart';
import 'package:wanflutter/event/events.dart';
import 'package:wanflutter/manager/app_manager.dart';
import 'package:wanflutter/ui/page/page_login.dart';

import '../../http/api.dart';

class WebViewPage extends StatefulWidget {

  final data;

  final supportCollect;

  /// 构造方法传入数据 参数
  WebViewPage(this.data, {this.supportCollect = false});

  @override
  _WebViewPageState createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {

  /// 网络数据加载中的标识
  bool isload = true;
  FlutterWebviewPlugin? flutterWebviewPlugin;

  /// 成员变量的初始化
  @override
  void initState() {
    super.initState();
    flutterWebviewPlugin = FlutterWebviewPlugin();
    /// 初始化浏览器的状态变化监听
    flutterWebviewPlugin?.onStateChanged.listen((event) {
      if(event.type == WebViewState.finishLoad) { //数据加载结束
        setState(() {
          isload = false;
        });
      }else if(event.type == WebViewState.startLoad) {
        setState(() {
          isload = true;
        });
      }
    });
  }

  @override
  void dispose() {
    flutterWebviewPlugin?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var isCollect = widget.data['collect']??false;
    /// 返回一个webview插件布局
    return WebviewScaffold(
        appBar: AppBar(
          title: Text(widget.data['title']),  // widget.data? widget是webviewpage自身这个控件
          actions: [
            Offstage(
              offstage: !widget.supportCollect,
              child: IconButton(
                icon: Icon(
                  Icons.favorite,
                  color: isCollect ? Colors.red : Colors.white,
                ),
                onPressed: () => _collect(),
              ),
            )
          ],

          ///appbar下边摆放的进度条
          bottom: PreferredSize(
            preferredSize: const Size.fromHeight(1.0),
            child: const LinearProgressIndicator()
          ),
          ///进度条的透明度
          bottomOpacity: isload?1.0:0.0,
        ),
        withLocalStorage: true, //打开缓存
        url: widget.data['url'],
        withJavascript: true,
    );
  }

  _collect() async {
    var result;
    bool isLogin = AppManager.isLogin();
    if(isLogin) {
      // 如果已收藏则取消收藏
      if(widget.data['collect']){
        result = await Api.unCollectArticle(widget.data['id']);
      } else {
        result = await Api.collectArticle(widget.data['id']);
      }
    } else {
      // pushReplacement 销毁当前页进入登录页
      Navigator.pushReplacement(context, MaterialPageRoute(builder: (_) => LoginPage()));
    }
    if(result['errorCode'] == 0){
      // 如果收藏功能成功，则刷新界面state
      setState(() {
        widget.data['collect'] = !widget.data['collect'];
        AppManager.eventBus.fire(CollectEvent(widget.data['id'], widget.data['collect']));
      });
    }
  }
}

